package ik.xcj.hostpital.manage.security;

import ik.xcj.hostpital.manage.mapper.UserMapper;
import ik.xcj.hostpital.manage.pojo.vo.UserLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper UserMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserLoginInfoVO loginInfoByUsername = UserMapper.getLoginInfoByUsername(s);

        if (loginInfoByUsername == null) {
            return null;
        }

        List<String> permissions = loginInfoByUsername.getPermissions();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String permission : permissions) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }

        UserDetails adminDetails = new UserDetails(loginInfoByUsername.getId(),
                loginInfoByUsername.getUsername(),
                loginInfoByUsername.getPassword(),
                loginInfoByUsername.getStatus() == 1,
                authorities);


        log.debug("即将向Spring Security返回UserDetails对象：{}", adminDetails);
        return adminDetails;
    }
}
